package org.example.common;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc:
 * @author: Ping
 * @date: 2023/11/13 15:25
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponse implements Serializable {
    private static final int SUCCESS_CODE = 0;//成功
    private static final int EXPIRES_CODE = 401;//登录过期
    private static final int NO_PERM_CODE = 403;//无权限
    private static final int NO_FIDE_CODE = 404;//未找到
    private static final int FAILURE_CODE = 500;//失败
    private static final int ERROR_PARAMS_CODE = 500;//失败
    private Integer code;
    private String msg;
    private Map<String, Object> data;

    public static ApiResponse getResponse(Integer code, String msg, HashMap<String, Object> map) {return new ApiResponse(code, msg, map);}
    public static ApiResponse ok(String msg, HashMap<String, Object> data) {return getResponse(SUCCESS_CODE, msg, data);}
    public static ApiResponse ok(String msg, String key, Object value) {return ok(msg, new HashMap<>(Map.of(key, value)));}
    public static ApiResponse ok(HashMap<String, Object> data) {
        return ok("success", data);
    }
    public static ApiResponse ok(String msg, Object value) {
        return ok(msg, new HashMap<>()).append("data", value);
    }
    public static ApiResponse ok(String msg) {
        return ok(msg, null);
    }
    public static ApiResponse ok(Object data) {
        return ok("data", data);
    }
    public static ApiResponse ok() {
        return ok("success", null);
    }
    public static ApiResponse failure() {
        return new ApiResponse(FAILURE_CODE, "failure", null);
    }
    public static ApiResponse failure(String msg) {
        return new ApiResponse(FAILURE_CODE, msg, null);
    }
    public static ApiResponse failure(String key, Object value) {return new ApiResponse(FAILURE_CODE, "failure", null).append(key, value);}
    public static ApiResponse noPermission(String perm_name) {return new ApiResponse(NO_PERM_CODE, "用户缺少" + perm_name + "权限", null);}
    public static ApiResponse certificationExpires() {
        return new ApiResponse(EXPIRES_CODE, "用户身份认证过期", null);
    }
    //直接返回数据，通常用于拦截器
    public static void returnDataDirectly(HttpServletResponse response, ApiResponse api) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().println(JSON.toJSON(api));
    }
    public ApiResponse append(String key, Object value) {
        if (ObjectUtils.isEmpty(this.data)) this.data = new HashMap<>();
        this.data.put(key, value);
        return ApiResponse.this;
    }
}
